package instantHelper.NormalMode;

import instantHelper.Models.CustomHttpClient;
import instantHelper.Raceway.*;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class NormalModeAudioRecorder extends Activity {



	public MediaRecorder mrec = null;
	private Button startRecording = null;
	private Button stopRecording = null;
	private static final String TAG = "NormalModeAudioRecorder";
	private String androidId;
	private int audioCount = 0;
	private static String requestId;
	File audiofile;
	String fileName = "default.3gp";
	String fileNameForFTP;


	ArrayList<String> audioPaths = new ArrayList<String>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.normalmode_audio);

		androidId = SettingsUtil.getAndroidID(getApplicationContext());
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			requestId = extras.getString("requestId");
		}

		/* Use the LocationManager class to obtain GPS locations */
		MyLocationListener.getGPSData(getApplicationContext(), androidId,requestId);

		mrec = new MediaRecorder();
		startRecording = (Button) findViewById(R.id.startrecording);
		stopRecording = (Button) findViewById(R.id.stoprecording);
		startRecording.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					startRecording.setEnabled(false);
					stopRecording.setEnabled(true);
					stopRecording.requestFocus();
					String fileName = createAudioPaths(androidId, requestId);
					audioCount++;
					startRecording();
				} catch (Exception ee) {
					Log.e(TAG, "Caught io exception " + ee.getMessage());
				}

			}

		});
		

		stopRecording.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startRecording.setEnabled(true);
				stopRecording.setEnabled(false);
				startRecording.requestFocus();
				stopRecording();
				try {
					sendAudioRequestToCentralAPP();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});

		stopRecording.setEnabled(false);
		startRecording.setEnabled(true);

	}

	protected void sendAudioFileViaFTP(String fileName2) {
		boolean issend = FTPHelper.sendToServer(fileName2, "audios/");
		if (issend) {
			if (SettingsUtil.getDeleteDataControl(getApplicationContext())) {
				SettingsUtil.deleteFile(fileName2);
			}
		} else {
			ContentValues contentValues = new ContentValues();
			Date time = new Date();
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_DATE,
					time.toString());
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_ISSEND, "0");
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_PATH,
					fileName2);
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_REQUEST_ID,
					requestId);
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_TYPE, "audio");
			// update
			DbHelper myDbHelper1 = new DbHelper(this);
			SQLiteDatabase db1 = myDbHelper1.getWritableDatabase();
			db1.insert(InstantHelperConstant.DB_DIRECTORY_TABLE, null,
					contentValues);
		}

	}

	protected String createAudioPaths(String androidId, String requestId) {
		fileName = "ihcenterapp/audios/audio_" + androidId + "_" + requestId
				+ "_" + audioCount + ".mp4";
		fileNameForFTP = "audio_" + androidId + "_" + requestId + "_"
				+ audioCount + ".mp4";
		fileName = sanitizePath(fileName);
		// make sure the directory we plan to store the recording in exists
		File directory = new File(fileName).getParentFile();
		if (!directory.exists() && !directory.mkdirs()) {
			try {
				throw new IOException("Path to file could not be created.");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		audioPaths.add(fileName);
		return fileName;
	}

	protected String sanitizePath(String path) {
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		if (!path.contains(".")) {
			path += ".mp4";
		}
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ path;
	}

	protected void startRecording() throws IOException {
		mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
		mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		mrec.setOutputFile(fileName);
		mrec.prepare();
		mrec.start();

	}

	private String sendAudioRequestToCentralAPP() throws IllegalStateException,
			IOException, URISyntaxException {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/newAudio";

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("audioPath", fileNameForFTP));
		postParameters.add(new BasicNameValuePair("requestId", requestId));
		postParameters.add(new BasicNameValuePair("androidId", androidId));
		String response = null;
		String result = "";
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			String res = response.toString();
			JSONObject jObject = new JSONObject(res);
			result = jObject.getString("result");
			Context context = getApplicationContext();

			if (result.equalsIgnoreCase("successfull")) {
				sendAudioFileViaFTP(fileName);
			}

		} catch (Exception e) {

		}
		return result;
	}

	protected void stopRecording() {
		mrec.stop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mrec.release();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mrec.release();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub

		super.onStop();
		mrec.release();
	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();

	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	}
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		finish();
		super.onBackPressed();
		
	}
	

}